package com.ycsj.goldmedalnewconcept.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.BirthdayInfo;
import com.ycsj.goldmedalnewconcept.utils.TimeUtil;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;
import com.ycsj.goldmedalnewconcept.view.RoundImageView;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * 创建日期：2017/11/15  9:00
 * 描述:学生生日列表的适配器
 * 作者:张伟
 */

public class BirthdayLvAdapter extends CommonAdapter<BirthdayInfo.ListBean> {

    private Context context;

    //网络请求错误的提示
    private static final int ERROR = 0X110;

    //发送请求成功的标识
    private static final int SUCCESS = 0X120;

    //发送请求失败的标识
    private static final int FAIL= 0X130;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ERROR:
                    UiHelper.toast(context, "网络错误");
                    break;
                case SUCCESS:
                    UiHelper.toast(context, "推送成功");
                    break;
                case FAIL:
                    UiHelper.toast(context, "推送");
                    break;
            }
        }
    };

    public BirthdayLvAdapter(Context context, List<BirthdayInfo.ListBean> datas, int layoutId) {
        super(context, datas, layoutId);
        this.context = context;
    }

    @Override
    public void convert(ViewHolder holder, final BirthdayInfo.ListBean info) {
        //用户头像
        RoundImageView lvHead = holder.getView(R.id.lv_head);
        Picasso.with(context).load(info.getIcon()).into(lvHead);
        //用户姓名
        TextView tvName = holder.getView(R.id.tv_name);
        tvName.setText(info.getName());

        LinearLayout llPos = holder.getView(R.id.ll_pos);
        llPos.setVisibility(View.GONE);

        //位置
        TextView tvPos = holder.getView(R.id.tv_pos);
        tvPos.setVisibility(View.GONE);

        //生日
        TextView tvBirthday = holder.getView(R.id.tv_birthday);
        tvBirthday.setText(TimeUtil.getMD(info.getBirthday()));

        //电话
        TextView tvPhone = holder.getView(R.id.tv_phone);
        tvPhone.setText(info.getUserId());

        //生日提醒的线性布局
        LinearLayout llMsg = holder.getView(R.id.ll_msg);

        //点击生日提醒的线性布局调用服务器接口进行推送接口请求
//        llMsg.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                new AlertDialog.Builder(context)
//                        .setTitle("生日快乐")
//                        .setMessage("确定发送生日提醒推送吗?")
//                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialogInterface, int i) {
//                                //调用服务器后台接口
////                               
//                                http(info, 1);
//                                http(info, 0);
//                            }
//                        })
//                        .setNegativeButton("取消", null)
//                        .show();
//            }
//        });
    }

    /**
     * 调用服务器后台推送生日接口
     *
     * @param info
     */
    private void http(BirthdayInfo.ListBean info, int flag) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("type", "32");
        builder.add("alias", info.getUserId() + flag + "");//0是学生 1是家长
        builder.add("content", getCotent());
        builder.add("title", "生日快乐");
        builder.add("ptype", "0");
        Request request = new Request.Builder()
                .url("http://pm.moregolden.com/ycsj_count/MessageCenter").post(builder.build())
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                handler.sendEmptyMessage(ERROR);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    //请求成功
                    //获取服务器返回的json数据
                    String json = response.body().string();
                    if(!TextUtils.isEmpty(json)){
                        JSONObject object = new JSONObject(json);
                        if(object.getInt("ResponseCode")==200){
                            //表示推送成功
                            handler.sendEmptyMessage(SUCCESS);
                            
                        }else{
                            //标识推送失败
                            handler.sendEmptyMessage(FAIL);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(ERROR);
                }
            }
        });
    }


    /**
     * 从字符串集合中随机取一个元素返回
     */
    private String getCotent() {
        List<String> contents = new ArrayList<>();
        contents.add("愿你像颗种子，勇敢地冲破泥沙，将嫩绿的幼芽伸出地面，指向天空。祝你生日快乐！");
        contents.add("祝你生日快乐，你的善良使这个世界变得更加美好，愿这完全属于你的一天带给你快乐，愿未来的日子锦上添花，学习进步！");
        contents.add("愿你是风，鼓起白色的帆；愿你是船，劈开蓝色的波澜。生活正在你的前方微笑，勇敢地走上前去，将彩色的人生拥抱，生日快乐！");
        contents.add("你长着一对翅膀，坚韧地飞吧，不要为风雨所折服；诚挚地飞吧，不要为香甜的蜜汁所陶醉。朝着明确的目标，飞向美好的人生，生日快乐！");
        contents.add("你长着一对翅膀，坚韧地飞吧，不要为风雨所折服；诚挚地飞吧，不要为香甜的蜜汁所陶醉。朝着明确的目标，飞向美好的人生，生日快乐！");
        contents.add("青春阳光欢笑，为这属于你的日子，舞出欢乐的节拍。祝你生日快乐！");

        Random random = new Random();
        int index = random.nextInt(contents.size() - 1);
        return contents.get(index);
    }
}
